﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;

namespace MNH.WebApps.Common.Helpers.JqGrid
{
    public class Grid : IHtmlString
    {
        private readonly List<Column> _columns = new List<Column>();
        private DataType _dataType = DataType.Json;
        private bool? _hideGrid = new bool?(false);
        private Dir? _direction = new Dir?(Dir.RTL);
        private int[] _rowList = new int[4]
            {
              10,
              15,
              20,
              50
            };
        private int? _rowNum = new int?(10);
        private bool? _rowNumbers = new bool?(true);
        private string _defaultSearch = "cn";
        private bool _searchOperators = true;
        private bool? _searchOnEnter = new bool?(true);
        private ToolbarPosition _toolbarPosition = ToolbarPosition.Top;
        private bool? _viewRecords = new bool?(true);
        private bool? _searchToggleButton = new bool?(true);
        private bool _stringResult = true;
        private readonly string _id;
        private string _altClass;
        private bool? _altRows;
        private bool? _autoEncode;
        private bool? _autoWidth;
        private string _caption;
        private string _emptyRecords;
        private bool? _footerRow;
        private bool? _userDataOnFooter;
        private bool? _forceFit;
        private bool? _gridView;
        private bool? _headerTitles;
        private int? _height;
        private bool? _hiddenGrid;
        private bool? _hoverRows;
        private bool? _loadOnce;
        private string _loadText;
        private LoadUi? _loadUi;
        private bool? _multiBoxOnly;
        private MultiKey? _multiKey;
        private bool? _multiSelect;
        private int? _multiSelectWidth;
        private string _onAfterInsertRow;
        private string _onBeforeRequest;
        private string _onBeforeSelectRow;
        private string _onCellSelect;
        private string _onDblClickRow;
        private string _onGridComplete;
        private string _onHeaderClick;
        private string _onLoadBeforeSend;
        private string _onLoadComplete;
        private string _onLoadError;
        private string _onPaging;
        private string _onResizeStart;
        private string _onResizeStop;
        private string _onRightClickRow;
        private string _onSelectAll;
        private string _onSelectRow;
        private string _onSerializeGridData;
        private string _onSortCol;
        private int? _page;
        private string _pager;
        private PagerPos? _pagerPos;
        private bool? _pgButtons;
        private bool? _pgInput;
        private string _pgText;
        private RecordPos? _recordPos;
        private string _recordText;
        private RequestType? _requestType;
        private string _resizeClass;
        private int? _rowNumWidth;
        private bool? _scroll;
        private int? _scrollInt;
        private int? _scrollOffset;
        private bool? _scrollRows;
        private int? _scrollTimeout;
        private bool? _searchClearButton;
        private bool? _searchToolbar;
        private bool? _showAllSortIcons;
        private bool? _shrinkToFit;
        private Direction? _sortIconDirection;
        private string _sortName;
        private bool? _sortOnHeaderClick;
        private SortOrder? _sortOrder;
        private bool? _toolbar;
        private bool? _topPager;
        private string _url;
        private int? _width;
        private JsonReader _jsonReader;
        private bool _enabledTreeGrid;
        private int? _treeGridRootLevel;
        private TreeGridModel _treeGridModel;
        private bool? _asyncLoad;
        private bool? _ignoreCase;
        private string _rowAttr;
        private string _exportButtonIcon;
        private string _exportUrl;

        public Grid(string id)
        {
            if (StringExtensions.IsNullOrWhiteSpace(id))
                throw new ArgumentException("Id must contain a value to identify the grid");
            this._id = id;
        }

        public Grid AddColumn(Column column)
        {
            column._gridId = _id;
            this._columns.Add(column);
            return this;
        }

        public Grid AddColumns(IEnumerable<Column> columns)
        {
            this._columns.AddRange(columns);
            return this;
        }

        public Grid SetAltClass(string altClass)
        {
            this._altClass = altClass;
            return this;
        }

        public Grid SetAltRows(bool altRows)
        {
            this._altRows = new bool?(altRows);
            return this;
        }

        public Grid SetAutoEncode(bool autoEncode)
        {
            this._autoEncode = new bool?(autoEncode);
            return this;
        }

        public Grid SetAutoWidth(bool autoWidth)
        {
            this._autoWidth = new bool?(autoWidth);
            return this;
        }

        public Grid SetCaption(string caption)
        {
            this._caption = caption;
            return this;
        }

        public Grid SetDataType(DataType dataType)
        {
            this._dataType = dataType;
            return this;
        }

        public Grid SetEmptyRecords(string emptyRecords)
        {
            this._emptyRecords = emptyRecords;
            return this;
        }

        public Grid SetFooterRow(bool footerRow)
        {
            this._footerRow = new bool?(footerRow);
            return this;
        }

        public Grid SetUserDataOnFooter(bool userDataOnFooter)
        {
            this._userDataOnFooter = new bool?(userDataOnFooter);
            return this;
        }

        public Grid SetForceFit(bool forceFit)
        {
            this._forceFit = new bool?(forceFit);
            return this;
        }

        public Grid SetGridView(bool gridView)
        {
            this._gridView = new bool?(gridView);
            return this;
        }

        public Grid SetHeaderTitles(bool headerTitles)
        {
            this._headerTitles = new bool?(headerTitles);
            return this;
        }

        public Grid SetHeight(int height)
        {
            this._height = new int?(height);
            return this;
        }

        public Grid SetHiddenGrid(bool hiddenGrid)
        {
            this._hiddenGrid = new bool?(hiddenGrid);
            return this;
        }

        public Grid SetHideGrid(bool hideGrid)
        {
            this._hideGrid = new bool?(hideGrid);
            return this;
        }

        public Grid SetHoverRows(bool hoverRows)
        {
            this._hoverRows = new bool?(hoverRows);
            return this;
        }

        public Grid SetLoadOnce(bool loadOnce)
        {
            this._loadOnce = new bool?(loadOnce);
            return this;
        }

        public Grid SetDirection(Dir direction)
        {
            this._direction = new Dir?(direction);
            return this;
        }

        public Grid SetLoadText(string loadText)
        {
            this._loadText = loadText;
            return this;
        }

        public Grid SetLoadUi(LoadUi loadUi)
        {
            this._loadUi = new LoadUi?(loadUi);
            return this;
        }

        public Grid SetMultiKey(MultiKey multiKey)
        {
            this._multiKey = new MultiKey?(multiKey);
            return this;
        }

        public Grid SetMultiBoxOnly(bool multiBoxOnly)
        {
            this._multiBoxOnly = new bool?(multiBoxOnly);
            return this;
        }

        public Grid SetMultiSelect(bool multiSelect)
        {
            this._multiSelect = new bool?(multiSelect);
            return this;
        }

        public Grid SetMultiSelectWidth(int multiSelectWidth)
        {
            this._multiSelectWidth = new int?(multiSelectWidth);
            return this;
        }

        public Grid SetPage(int page)
        {
            this._page = new int?(page);
            return this;
        }

        public Grid SetPager(string pager)
        {
            this._pager = pager;
            return this;
        }

        public Grid SetPagerPos(PagerPos pagerPos)
        {
            this._pagerPos = new PagerPos?(pagerPos);
            return this;
        }

        public Grid SetPgButtons(bool pgButtons)
        {
            this._pgButtons = new bool?(pgButtons);
            return this;
        }

        public Grid SetPgInput(bool pgInput)
        {
            this._pgInput = new bool?(pgInput);
            return this;
        }

        public Grid SetPgText(string pgText)
        {
            this._pgText = pgText;
            return this;
        }

        public Grid SetRecordPos(RecordPos recordPos)
        {
            this._recordPos = new RecordPos?(recordPos);
            return this;
        }

        public Grid SetRecordText(string recordText)
        {
            this._recordText = recordText;
            return this;
        }

        public Grid SetRequestType(RequestType requestType)
        {
            this._requestType = new RequestType?(requestType);
            return this;
        }

        public Grid SetResizeClass(string resizeClass)
        {
            this._resizeClass = resizeClass;
            return this;
        }

        public Grid SetRowList(int[] rowList)
        {
            this._rowList = rowList;
            return this;
        }

        public Grid SetRowNum(int rowNum)
        {
            this._rowNum = new int?(rowNum);
            return this;
        }

        public Grid SetRowNumbers(bool rowNumbers)
        {
            this._rowNumbers = new bool?(rowNumbers);
            return this;
        }

        public Grid SetRowNumWidth(int rowNumWidth)
        {
            this._rowNumWidth = new int?(rowNumWidth);
            return this;
        }

        [Obsolete("Method is obsolete, use SetVirtualScroll instead")]
        public Grid SetScroll(bool scroll)
        {
            this._scroll = new bool?(scroll);
            return this;
        }

        [Obsolete("Method is obsolete, use SetVirtualScroll instead")]
        public Grid SetScroll(int scroll)
        {
            this._scrollInt = new int?(scroll);
            return this;
        }

        public Grid SetStringResult(bool stringResult)
        {
            this._stringResult = stringResult;
            return this;
        }

        public Grid SetVirtualScroll(bool virtualScroll, bool justHoldVisibleLines = true)
        {
            if (virtualScroll && justHoldVisibleLines)
                this._scrollInt = new int?(1);
            else
                this._scroll = virtualScroll ? new bool?(true) : new bool?(false);
            return this;
        }

        public Grid SetScrollOffset(int scrollOffset)
        {
            this._scrollOffset = new int?(scrollOffset);
            return this;
        }

        public Grid SetScrollRows(bool scrollRows)
        {
            this._scrollRows = new bool?(scrollRows);
            return this;
        }

        public Grid SetScrollTimeout(int scrollTimeout)
        {
            this._scrollTimeout = new int?(scrollTimeout);
            return this;
        }

        public Grid SetShrinkToFit(bool shrinkToFit)
        {
            this._shrinkToFit = new bool?(shrinkToFit);
            return this;
        }

        public Grid SetSearchOnEnter(bool searchOnEnter)
        {
            this._searchOnEnter = new bool?(searchOnEnter);
            return this;
        }

        public Grid SetDefaultSearch(string defaultSearch)
        {
            this._defaultSearch = defaultSearch;
            return this;
        }

        public Grid SetSearchToolbar(bool searchToolbar)
        {
            this._searchToolbar = new bool?(searchToolbar);
            return this;
        }

        public Grid SetSearchClearButton(bool searchClearButton)
        {
            this._searchClearButton = new bool?(searchClearButton);
            return this;
        }

        public Grid SetSearchToggleButton(bool searchToggleButton)
        {
            this._searchToggleButton = new bool?(searchToggleButton);
            return this;
        }

        public Grid SetShowAllSortIcons(bool showAllSortIcons)
        {
            this._showAllSortIcons = new bool?(showAllSortIcons);
            return this;
        }

        public Grid SetSortIconDirection(Direction sortIconDirection)
        {
            this._sortIconDirection = new Direction?(sortIconDirection);
            return this;
        }

        public Grid SetSortOnHeaderClick(bool sortOnHeaderClick)
        {
            this._sortOnHeaderClick = new bool?(sortOnHeaderClick);
            return this;
        }

        public Grid SetSortName(string sortName)
        {
            this._sortName = sortName;
            return this;
        }

        public Grid SetSortOrder(SortOrder sortOrder)
        {
            this._sortOrder = new SortOrder?(sortOrder);
            return this;
        }

        public Grid SetToolbar(bool toolbar)
        {
            this._toolbar = new bool?(toolbar);
            return this;
        }

        public Grid SetToolbarPosition(ToolbarPosition toolbarPosition)
        {
            this._toolbarPosition = toolbarPosition;
            return this;
        }

        public Grid SetTopPager(bool topPager)
        {
            this._topPager = new bool?(topPager);
            return this;
        }

        public Grid SetUrl(string url)
        {
            this._url = url;
            return this;
        }

        public Grid SetViewRecords(bool viewRecords)
        {
            this._viewRecords = new bool?(viewRecords);
            return this;
        }

        public Grid SetWidth(int width)
        {
            this._width = new int?(width);
            return this;
        }

        public Grid SetAsyncLoad(bool asyncPageLoad)
        {
            this._asyncLoad = new bool?(asyncPageLoad);
            return this;
        }

        public Grid SetIgnoreCase(bool ignoreCase)
        {
            this._ignoreCase = new bool?(ignoreCase);
            return this;
        }

        public Grid OnAfterInsertRow(string onAfterInsertRow)
        {
            this._onAfterInsertRow = onAfterInsertRow;
            return this;
        }

        public Grid OnBeforeRequest(string onBeforeRequest)
        {
            this._onBeforeRequest = onBeforeRequest;
            return this;
        }

        public Grid OnBeforeSelectRow(string onBeforeSelectRow)
        {
            this._onBeforeSelectRow = onBeforeSelectRow;
            return this;
        }

        public Grid OnGridComplete(string onGridComplete)
        {
            this._onGridComplete = onGridComplete;
            return this;
        }

        public Grid OnLoadBeforeSend(string onLoadBeforeSend)
        {
            this._onLoadBeforeSend = onLoadBeforeSend;
            return this;
        }

        public Grid OnLoadComplete(string onLoadComplete)
        {
            this._onLoadComplete = onLoadComplete;
            return this;
        }

        public Grid OnLoadError(string onLoadError)
        {
            this._onLoadError = onLoadError;
            return this;
        }

        public Grid OnCellSelect(string onCellSelect)
        {
            this._onCellSelect = onCellSelect;
            return this;
        }

        public Grid OnDblClickRow(string onDblClickRow)
        {
            this._onDblClickRow = onDblClickRow;
            return this;
        }

        public Grid OnHeaderClick(string onHeaderClick)
        {
            this._onHeaderClick = onHeaderClick;
            return this;
        }

        public Grid OnPaging(string onPaging)
        {
            this._onPaging = onPaging;
            return this;
        }

        public Grid OnRightClickRow(string onRightClickRow)
        {
            this._onRightClickRow = onRightClickRow;
            return this;
        }

        public Grid OnSelectAll(string onSelectAll)
        {
            this._onSelectAll = onSelectAll;
            return this;
        }

        public Grid OnSelectRow(string onSelectRow)
        {
            this._onSelectRow = onSelectRow;
            return this;
        }

        public Grid OnSortCol(string onSortCol)
        {
            this._onSortCol = onSortCol;
            return this;
        }

        public Grid OnResizeStart(string onResizeStart)
        {
            this._onResizeStart = onResizeStart;
            return this;
        }

        public Grid OnResizeStop(string onResizeStop)
        {
            this._onResizeStop = onResizeStop;
            return this;
        }

        public Grid OnSerializeGridData(string onSerializeGridData)
        {
            this._onSerializeGridData = onSerializeGridData;
            return this;
        }

        public Grid SetJsonReader(JsonReader jsonReader)
        {
            this._jsonReader = jsonReader;
            return this;
        }

        public Grid EnableTreeGrid(TreeGridModel treeGridModel = TreeGridModel.Adjacency, int rootLevel = 0)
        {
            this._treeGridRootLevel = new int?(0);
            this._enabledTreeGrid = true;
            this._treeGridModel = treeGridModel;
            return this;
        }

        public Grid SetRowAttr(string rowAttr)
        {
            this._rowAttr = rowAttr;
            return this;
        }

        public Grid AddExportButton(string buttonicon, string url)
        {
            _exportButtonIcon = string.IsNullOrEmpty(buttonicon) ? "ui-icon-print" : buttonicon;
            _exportUrl = url;
            return this;
        }


        public string RenderJavascript()
        {
            StringBuilder stringBuilder = new StringBuilder();
            if (this._asyncLoad.HasValue && this._asyncLoad.Value)
                stringBuilder.AppendLine("jQuery(window).ready(function () {");
            else
                stringBuilder.AppendLine("jQuery(document).ready(function () {");
            stringBuilder.AppendLine("jQuery('#" + this._id + "').jqGrid({");
            if (Enumerable.Count<Column>((IEnumerable<Column>)this._columns, (Func<Column, bool>)(r => r.IsKey)) > 1)
                throw new ArgumentException("Too many key columns added. Maximum allowed id 1.");
            if (this._altRows.HasValue)
                stringBuilder.AppendFormat("altRows:{0},", this._altRows.ToString().ToLower()).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._altClass))
                stringBuilder.AppendFormat("altclass:'{0}',", this._altClass).AppendLine();
            if (this._autoEncode.HasValue)
                stringBuilder.AppendFormat("autoencode:{0},", this._autoEncode.ToString().ToLower()).AppendLine();
            if (this._autoWidth.HasValue)
                stringBuilder.AppendFormat("autowidth:{0},", this._autoWidth.ToString().ToLower()).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._caption))
                stringBuilder.AppendFormat("caption:'{0}',", this._caption).AppendLine();
            stringBuilder.AppendLine(this._enabledTreeGrid ? string.Format("treedatatype:'{0}',", (this._dataType).ToString().ToLower()) : string.Format("datatype:'{0}',", (this._dataType).ToString().ToLower()));
            if (this._dataType == DataType.Json && this._jsonReader != null)
                stringBuilder.AppendLine("jsonReader:{'repeatitems':" + this._jsonReader.RepeatItems.ToString().ToLower() + ", 'id': '" + this._jsonReader.Id + "' },");
            if (!StringExtensions.IsNullOrWhiteSpace(this._emptyRecords))
                stringBuilder.AppendFormat("emptyrecords:'{0}',", this._emptyRecords).AppendLine();
            if (this._footerRow.HasValue)
                stringBuilder.AppendFormat("footerrow:{0},", this._footerRow.ToString().ToLower()).AppendLine();
            if (this._userDataOnFooter.HasValue)
                stringBuilder.AppendFormat("userDataOnFooter:{0},", this._footerRow.ToString().ToLower()).AppendLine();
            if (this._forceFit.HasValue)
                stringBuilder.AppendFormat("forceFit:{0},", this._forceFit.ToString().ToLower()).AppendLine();
            if (this._gridView.HasValue)
                stringBuilder.AppendFormat("gridview:{0},", this._gridView.ToString().ToLower()).AppendLine();
            if (this._headerTitles.HasValue)
                stringBuilder.AppendFormat("headertitles:{0},", this._headerTitles.ToString().ToLower()).AppendLine();
            bool? nullable;
            if (!this._height.HasValue)
            {
                int num;
                if (this._scroll.HasValue)
                {
                    nullable = this._scroll;
                    if ((nullable.GetValueOrDefault() ? 0 : (nullable.HasValue ? 1 : 0)) == 0)
                    {
                        num = 1;
                        goto label_34;
                    }
                }
                num = this._scrollInt.HasValue ? 1 : 0;
            label_34:
                if (num == 0)
                    stringBuilder.AppendFormat("height:'{0}',", "100%").AppendLine();
            }
            else
                stringBuilder.AppendFormat("height:{0},", this._height).AppendLine();
            if (this._hiddenGrid.HasValue)
                stringBuilder.AppendFormat("hiddengrid:{0},", this._hiddenGrid.ToString().ToLower()).AppendLine();
            if (this._hideGrid.HasValue)
                stringBuilder.AppendFormat("hidegrid:{0},", this._hideGrid.ToString().ToLower()).AppendLine();
            if (this._hoverRows.HasValue)
                stringBuilder.AppendFormat("hoverrows:{0},", this._hoverRows.ToString().ToLower()).AppendLine();
            if (this._loadOnce.HasValue)
                stringBuilder.AppendFormat("loadonce:{0},", this._loadOnce.ToString().ToLower()).AppendLine();
            if (this._direction.HasValue)
                stringBuilder.AppendFormat("direction:'{0}',", this._direction.ToString().ToLower()).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._loadText))
                stringBuilder.AppendFormat("loadtext:'{0}',", this._loadText).AppendLine();
            if (this._loadUi.HasValue)
                stringBuilder.AppendFormat("loadui:'{0}',", this._loadUi.ToString().ToLower()).AppendLine();
            if (this._multiBoxOnly.HasValue)
                stringBuilder.AppendFormat("multiboxonly:{0},", this._multiBoxOnly.ToString().ToLower()).AppendLine();
            if (this._multiKey.HasValue)
                stringBuilder.AppendFormat("multikey:'{0}',", this._multiKey.ToString().ToLower()).AppendLine();
            if (this._multiSelect.HasValue)
                stringBuilder.AppendFormat("multiselect:{0},", this._multiSelect.ToString().ToLower()).AppendLine();
            if (this._multiSelectWidth.HasValue)
                stringBuilder.AppendFormat("multiselectWidth:{0},", this._multiSelectWidth).AppendLine();
            if (this._page.HasValue)
                stringBuilder.AppendFormat("page:{0},", this._page).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._pager))
                stringBuilder.AppendFormat("pager:'#{0}',", this._pager).AppendLine();
            if (this._pagerPos.HasValue)
                stringBuilder.AppendFormat("pagerpos:'{0}',", this._pagerPos.ToString().ToLower()).AppendLine();
            if (this._pgButtons.HasValue)
                stringBuilder.AppendFormat("pgbuttons:{0},", this._pgButtons.ToString().ToLower()).AppendLine();
            if (this._pgInput.HasValue)
                stringBuilder.AppendFormat("pginput:{0},", this._pgInput.ToString().ToLower()).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._pgText))
                stringBuilder.AppendFormat("pgtext:'{0}',", this._pgText).AppendLine();
            if (this._recordPos.HasValue)
                stringBuilder.AppendFormat("recordpos:'{0}',", this._recordPos.ToString().ToLower()).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._recordText))
                stringBuilder.AppendFormat("recordtext:'{0}',", this._recordText).AppendLine();
            if (this._requestType.HasValue)
                stringBuilder.AppendFormat("mtype:'{0}',", this._requestType.ToString().ToLower()).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._resizeClass))
                stringBuilder.AppendFormat("resizeclass:'{0}',", this._resizeClass).AppendLine();
            if (this._rowList != null)
                stringBuilder.AppendFormat("rowList:[{0}],", string.Join(",", Enumerable.ToArray<string>(Enumerable.Select<int, string>((IEnumerable<int>)this._rowList, (Func<int, string>)(p => p.ToString()))))).AppendLine();
            if (this._rowNum.HasValue)
                stringBuilder.AppendFormat("rowNum:{0},", this._rowNum).AppendLine();
            if (this._rowNumbers.HasValue)
                stringBuilder.AppendFormat("rownumbers:{0},", this._rowNumbers.ToString().ToLower()).AppendLine();
            if (this._rowNumWidth.HasValue)
                stringBuilder.AppendFormat("rownumWidth:{0},", this._rowNumWidth).AppendLine();
            if (this._scrollInt.HasValue)
                stringBuilder.AppendFormat("scroll:{0},", this._scrollInt).AppendLine();
            else if (this._scroll.HasValue)
                stringBuilder.AppendFormat("scroll:{0},", this._scroll.ToString().ToLower()).AppendLine();
            if (this._scrollOffset.HasValue)
                stringBuilder.AppendFormat("scrollOffset:{0},", this._scrollOffset).AppendLine();
            if (this._scrollRows.HasValue)
                stringBuilder.AppendFormat("scrollrows:{0},", this._scrollRows.ToString().ToLower()).AppendLine();
            if (this._scrollTimeout.HasValue)
                stringBuilder.AppendFormat("scrollTimeout:{0},", this._scrollTimeout).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._sortName))
                stringBuilder.AppendFormat("sortname:'{0}',", this._sortName).AppendLine();
            if (this._showAllSortIcons.HasValue || this._sortIconDirection.HasValue || this._sortOnHeaderClick.HasValue)
            {
                if (!this._showAllSortIcons.HasValue)
                    this._showAllSortIcons = new bool?(false);
                if (!this._sortIconDirection.HasValue)
                    this._sortIconDirection = new Direction?(Direction.Vertical);
                if (!this._sortOnHeaderClick.HasValue)
                    this._sortOnHeaderClick = new bool?(true);
                stringBuilder.AppendFormat("viewsortcols:[{0},'{1}',{2}],", this._showAllSortIcons.ToString().ToLower(), this._sortIconDirection.ToString().ToLower(), this._sortOnHeaderClick.ToString().ToLower()).AppendLine();
            }
            if (this._shrinkToFit.HasValue)
                stringBuilder.AppendFormat("shrinkToFit:{0},", this._shrinkToFit.ToString().ToLower()).AppendLine();
            if (this._sortOrder.HasValue)
                stringBuilder.AppendFormat("sortorder:'{0}',", this._sortOrder.ToString().ToLower()).AppendLine();
            if (this._toolbar.HasValue)
                stringBuilder.AppendFormat("toolbar:[{0},'{1}'],", this._toolbar.ToString().ToLower(), (this._toolbarPosition).ToString().ToLower()).AppendLine();
            if (this._topPager.HasValue)
                stringBuilder.AppendFormat("toppager:{0},", this._topPager.ToString().ToLower()).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._url))
                stringBuilder.AppendFormat("url:'{0}',", this._url).AppendLine();
            if (this._viewRecords.HasValue)
                stringBuilder.AppendFormat("viewrecords:{0},", this._viewRecords.ToString().ToLower()).AppendLine();
            if (this._width.HasValue)
                stringBuilder.AppendFormat("width:'{0}',", this._width).AppendLine();
            if (this._ignoreCase.HasValue)
                stringBuilder.AppendFormat("ignoreCase:{0},", this._ignoreCase.ToString().ToLower()).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._onAfterInsertRow))
                stringBuilder.AppendFormat("afterInsertRow: function(rowid, rowdata, rowelem) {{{0}}},", this._onAfterInsertRow).AppendLine();
            if (Enumerable.Any<Column>((IEnumerable<Column>)this._columns, (Func<Column, bool>)(x => x.HasDefaultSearchValue)))
            {
                string str = "\r\n                function() {\r\n                        var defaultValueColumns = " + new JavaScriptSerializer().Serialize(Enumerable.Select(Enumerable.Where<Column>((IEnumerable<Column>)this._columns, (Func<Column, bool>)(x => x.HasDefaultSearchValue)), x =>
                {
                    var fAnonymousType0 = new
                    {
                        field = x.Index,
                        op = x.SearchOption,
                        data = x.DefaultSearchValue
                    };
                    return fAnonymousType0;
                })) + ";\r\n                        var colModel = this.p.colModel;\r\n\r\n                        if (defaultValueColumns.length > 0) {\r\n                            var postData = this.p.postData;\r\n\r\n                            var filters = {};\r\n\r\n                            if (postData.hasOwnProperty('filters')) {\r\n                                filters = JSON.parse(postData.filters);\r\n                            }\r\n\r\n                            var rules = [];\r\n\r\n                            if (filters.hasOwnProperty('rules')) {\r\n                                rules = filters.rules;\r\n                            }\r\n\r\n                            $.each(defaultValueColumns, function (defaultValueColumnIndex, defaultValueColumn) {\r\n                                $.each(rules, function (index, rule) {\r\n                                    if (defaultValueColumn.field == rule.field) {\r\n                                        delete rules[index];\r\n                                        return;\r\n                                    }\r\n                                });\r\n\r\n                                rules.push(defaultValueColumn);\r\n                            });\r\n\r\n                            filters.groupOp = 'AND';\r\n                            filters.rules = rules;\r\n\r\n                            postData._search = true;\r\n                            postData.filters = JSON.stringify(filters);\r\n\r\n                            $(this).setGridParam({ search: true, 'postData': postData});\r\n                        }\r\n\r\n                        this.p.beforeRequest = function() { " + (!StringExtensions.IsNullOrWhiteSpace(this._onBeforeRequest) ? this._onBeforeRequest : "") + " };\r\n                        this.p.beforeRequest.call(this);\r\n                    } ";
                stringBuilder.AppendFormat("beforeRequest: {0},", str).AppendLine();
            }
            else if (!StringExtensions.IsNullOrWhiteSpace(this._onBeforeRequest))
                stringBuilder.AppendFormat("beforeRequest: function() {{{0}}},", this._onBeforeRequest).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._onBeforeSelectRow))
                stringBuilder.AppendFormat("beforeSelectRow: function(rowid, e) {{{0}}},", this._onBeforeSelectRow).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._onGridComplete))
                stringBuilder.AppendFormat("gridComplete: function() {{{0}}},", this._onGridComplete).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._onLoadBeforeSend))
                stringBuilder.AppendFormat("loadBeforeSend: function(xhr, settings) {{{0}}},", this._onLoadBeforeSend).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._onLoadComplete))
                stringBuilder.AppendFormat("loadComplete: function(xhr) {{{0}}},", this._onLoadComplete).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._onLoadError))
                stringBuilder.AppendFormat("loadError: function(xhr, status, error) {{{0}}},", this._onLoadError).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._onCellSelect))
                stringBuilder.AppendFormat("onCellSelect: function(rowid, iCol, cellcontent, e) {{{0}}},", this._onCellSelect).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._onDblClickRow))
                stringBuilder.AppendFormat("ondblClickRow: function(rowid, iRow, iCol, e) {{{0}}},", this._onDblClickRow).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._onHeaderClick))
                stringBuilder.AppendFormat("onHeaderClick: function(gridstate) {{{0}}},", this._onHeaderClick).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._onPaging))
                stringBuilder.AppendFormat("onPaging: function(pgButton) {{{0}}},", this._onPaging).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._onRightClickRow))
                stringBuilder.AppendFormat("onRightClickRow: function(rowid, iRow, iCol, e) {{{0}}},", this._onRightClickRow).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._onSelectAll))
                stringBuilder.AppendFormat("onSelectAll: function(aRowids, status) {{{0}}},", this._onSelectAll).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._onSelectRow))
                stringBuilder.AppendFormat("onSelectRow: function(rowid, status) {{{0}}},", this._onSelectRow).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._onSortCol))
                stringBuilder.AppendFormat("onSortCol: function(index, iCol, sortorder) {{{0}}},", this._onSortCol).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._onResizeStart))
                stringBuilder.AppendFormat("resizeStart: function(jqGridEvent, index) {{{0}}},", this._onResizeStart).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._onResizeStop))
                stringBuilder.AppendFormat("resizeStop: function(newwidth, index) {{{0}}},", this._onResizeStop).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._onSerializeGridData))
                stringBuilder.AppendFormat("serializeGridData: function(postData) {{{0}}},", this._onSerializeGridData).AppendLine();
            if (!StringExtensions.IsNullOrWhiteSpace(this._rowAttr))
                stringBuilder.AppendFormat("rowattr: function(rd) {{{0}}},", this._rowAttr).AppendLine();
            if (this._enabledTreeGrid)
            {
                if (Enumerable.Count<Column>((IEnumerable<Column>)this._columns, (Func<Column, bool>)(r => r.IsExpandable)) > 1)
                    throw new ArgumentException("Too many key columns set as expandable. Maximum allowed is 1.");
                Column column1 = Enumerable.FirstOrDefault<Column>((IEnumerable<Column>)this._columns, (Func<Column, bool>)(r => r.IsKey));
                Column column2 = Enumerable.FirstOrDefault<Column>((IEnumerable<Column>)this._columns, (Func<Column, bool>)(r => r.IsExpandable));
                if (column1 == null)
                    throw new ArgumentException("Enabling treegrid needs at least one column set as Key.");
                if (column2 == null)
                    throw new ArgumentException("Enabling treegrid needs at least one column set as expandable.");
                stringBuilder.AppendLine("treeGrid: true,");
                stringBuilder.AppendFormat("ExpandColumn : '{0}',", column2.Name).AppendLine();
                stringBuilder.AppendFormat("treeGridModel : '{0}',", (this._treeGridModel).ToString().ToLower()).AppendLine();
                stringBuilder.AppendFormat("tree_root_level : {0},", this._treeGridRootLevel).AppendLine();
            }
            stringBuilder.AppendLine("colModel: [");
            string str1 = string.Join(",", Enumerable.ToArray<string>(Enumerable.Select<Column, string>((IEnumerable<Column>)this._columns, (Func<Column, string>)(c => c.ToString()))));
            stringBuilder.AppendLine(str1);
            stringBuilder.AppendLine("]");
            stringBuilder.AppendLine("});");
            nullable = this._searchToolbar;
            int num1;
            if ((!nullable.GetValueOrDefault() ? 0 : (nullable.HasValue ? 1 : 0)) != 0 && !StringExtensions.IsNullOrWhiteSpace(this._pager))
            {
                if (this._searchClearButton.HasValue)
                {
                    nullable = this._searchClearButton;
                    if ((!nullable.GetValueOrDefault() ? 0 : (nullable.HasValue ? 1 : 0)) != 0)
                    {
                        num1 = 0;
                        goto label_179;
                    }
                }
                if (this._searchToggleButton.HasValue)
                {
                    nullable = this._searchToggleButton;
                    num1 = (!nullable.GetValueOrDefault() ? 0 : (nullable.HasValue ? 1 : 0)) == 0 ? 1 : 0;
                }
                else
                    num1 = 1;
            }
            else
                num1 = 1;
        label_179:
            if (num1 == 0)
                stringBuilder.AppendLine("jQuery('#" + this._id + "').jqGrid('navGrid',\"#" + this._pager + "\",{edit:false,add:false,del:false,search:false,refresh:true}); ");
            nullable = this._searchToolbar;
            int num2;
            if ((!nullable.GetValueOrDefault() ? 0 : (nullable.HasValue ? 1 : 0)) != 0 && this._searchClearButton.HasValue && !StringExtensions.IsNullOrWhiteSpace(this._pager))
            {
                nullable = this._searchClearButton;
                num2 = (!nullable.GetValueOrDefault() ? 0 : (nullable.HasValue ? 1 : 0)) == 0 ? 1 : 0;
            }
            else
                num2 = 1;
            if (num2 == 0)
                stringBuilder.AppendLine("jQuery('#" + this._id + "').jqGrid('navButtonAdd',\"#" + this._pager + "\",{caption:\"حذف فیلترها\",title:\"حذف فیلترها\",buttonicon :'ui-icon-refresh', onClickButton:function(){jQuery('#" + this._id + "')[0].clearToolbar(); }}); ");
            nullable = this._searchToolbar;
            int num3;
            if ((!nullable.GetValueOrDefault() ? 0 : (nullable.HasValue ? 1 : 0)) != 0 && this._searchToggleButton.HasValue && !StringExtensions.IsNullOrWhiteSpace(this._pager))
            {
                nullable = this._searchToggleButton;
                num3 = (!nullable.GetValueOrDefault() ? 0 : (nullable.HasValue ? 1 : 0)) == 0 ? 1 : 0;
            }
            else
                num3 = 1;
            if (num3 == 0)
                stringBuilder.AppendLine("jQuery('#" + this._id + "').jqGrid('navButtonAdd',\"#" + this._pager + "\",{caption:\"جستجو\",title:\"جستجو\",buttonicon :'ui-icon-search', onClickButton:function(){jQuery('#" + this._id + "')[0].toggleToolbar(); }}); ");

            if (!string.IsNullOrEmpty(_exportUrl))
            {
                stringBuilder.AppendLine("jQuery('#" + this._id + "').jqGrid('navButtonAdd',\"#" + this._pager + "\",{caption:\"\",title:\"خروجی PDF , Excel\",buttonicon :'" + _exportButtonIcon + "', onClickButton:function(){jQuery('#" + this._id + "').jqGrid('excelExport', { url: '"+_exportUrl+"' }); }}); ");
            }
            //.jqGrid('navButtonAdd', '#pager', {
            //                caption: "", buttonicon: "ui-icon-print", title: "خروجي پي دي اف",
            //                onClickButton: function () {
            //                   
            //                }
            //            });
            nullable = this._searchToolbar;
            if ((!nullable.GetValueOrDefault() ? 0 : (nullable.HasValue ? 1 : 0)) != 0)
            {
                stringBuilder.Append("jQuery('#" + this._id + "').jqGrid('filterToolbar', {stringResult:" + this._stringResult.ToString().ToLower());
                if (this._searchOnEnter.HasValue)
                    stringBuilder.AppendFormat(", searchOnEnter:{0}", this._searchOnEnter.ToString().ToLower());
                stringBuilder.AppendFormat(", defaultSearch:\"{0}\"", (this._defaultSearch).ToString().ToLower());
                stringBuilder.AppendFormat(", searchOperators:\"{0}\"", (this._searchOperators).ToString().ToLower());
                stringBuilder.AppendLine("});");
            }
            stringBuilder.AppendLine("});");
            stringBuilder.Replace("##gridid##", this._id);
            return (stringBuilder).ToString();
        }

        public string RenderHtmlElements()
        {
            StringBuilder stringBuilder1 = new StringBuilder();
            stringBuilder1.AppendFormat("<table id=\"{0}\"></table>", this._id);
            StringBuilder stringBuilder2 = new StringBuilder();
            if (!StringExtensions.IsNullOrWhiteSpace(this._pager))
                stringBuilder2.AppendFormat("<div id=\"{0}\"></div>", this._pager);
            StringBuilder stringBuilder3 = new StringBuilder();
            bool? nullable = this._topPager;
            if ((!nullable.GetValueOrDefault() ? 0 : (nullable.HasValue ? 1 : 0)) != 0)
                stringBuilder3.AppendFormat("<div id=\"{0}_toppager\"></div>", this._id);
            return stringBuilder1.ToString() + stringBuilder2.ToString() + stringBuilder3.ToString();
        }

        public override string ToString()
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.AppendLine("<script type=\"text/javascript\">");
            stringBuilder.Append(this.RenderJavascript());
            stringBuilder.AppendLine("</script>");
            stringBuilder.Replace("##gridid##", this._id);
            return stringBuilder.ToString() + this.RenderHtmlElements();
        }

        public string ToHtmlString()
        {
            return this.ToString();
        }
    }
}
